package com.easy.payment.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayApiException;
import com.easy.bean.Orders;
import com.easy.common.CommonResult;
import com.easy.config.SYSConfig;
import com.easy.exception.OrderOutTimeException;
import com.easy.payment.service.IPaymentService;
import com.easy.payment.service.OrderFeignService;
import com.easy.payment.service.RedisFeignService;
import com.easy.payment.service.UserFeignService;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;

@RequestMapping("payment")
@RestController
@CrossOrigin
public class PaymentController {

    @Autowired
    IPaymentService zfbPS;

    @Autowired
    UserFeignService userFS;
    @Autowired
    RedisFeignService redisFS;
    @Autowired
    OrderFeignService orderFS;
    /**
     * 预支付请求
     */
    @RequestMapping(value = "prepayment",method = RequestMethod.POST)
    public String prePayment(@RequestBody Orders order) throws AlipayApiException {
        String result=zfbPS.prePayment(order);
        return result;
    }
    
    @RequestMapping(value = "paymentorder",method = RequestMethod.GET)
    public String prePaymentByOrderID(int orderid) throws AlipayApiException, OrderOutTimeException {
        String result=null;
        String key=SYSConfig.ORDER_PAYMENT_PRE_REDIS_KEY+orderid;
        result=redisFS.getVal(key);
        if(result!=null) {
        	return result;
        }
        result=zfbPS.prePaymentByOrderID(orderid);
        return result;
    }


    /**
     * 支付成功回调
     */
    @RequestMapping(value="/success",method=RequestMethod.POST)
    public void paymentSuccess(@RequestParam HashMap<String,String> params) {
    	System.out.println("------------success------------");
    	//修改订单状态
    	String orderidstr=params.get("out_trade_no");
    	int orderid=Integer.parseInt(orderidstr);
    	orderFS.changeOrderStatus(orderid, 2);
    	System.out.println(params.keySet());
    	//删除redis支付地址缓存
    	String key=SYSConfig.ORDER_PAYMENT_PRE_REDIS_KEY+orderid;
        redisFS.deleteVal(key);
    	System.out.println(params.get("out_trade_no"));
    	//redis中记录已经支付成功
    	key=SYSConfig.ORDER_PAYMENT_SUCCESS_REDIS_KEY+orderid;
    	redisFS.setValExpire(key, "success", 30, "S");    	
    }
    @RequestMapping(value="/check/{orderid}",method=RequestMethod.GET)
    public CommonResult checkOrderPayment(@PathVariable int orderid) {
    	String	key=SYSConfig.ORDER_PAYMENT_SUCCESS_REDIS_KEY+orderid;
    	String result=redisFS.getVal(key);
    	if(result=="success") {
    		return CommonResult.success();
    	}else {
    		Orders order=orderFS.getOrderByID(orderid);
    		if(order!=null&&order.getStatus()>=2) {
    			return CommonResult.success();
    		}
    		 return CommonResult.failed();
    	}
    }
    
    /**
     * 获取支付二维码
     * @param request
     * @param response
     * @return Base64编码
     * @throws IOException
     */
    @RequestMapping(value = "paymentimage/{orderid}",method = RequestMethod.GET)
    public CommonResult paymentImage(@PathVariable int orderid)  {
        String url;
		try {
			url = prePaymentByOrderID(orderid);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return CommonResult.failed(400, "系统异常");
		} catch (OrderOutTimeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return CommonResult.failed(400, "订单超时");
		}
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        //将url转换成图片
        QrCodeUtil.generate(url, 300, 300, ImgUtil.IMAGE_TYPE_JPG,outputStream);
        String base= Base64.getEncoder().encodeToString(outputStream.toByteArray());
        return CommonResult.success(base);
    }
}
